package models

import (
	"fmt"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type Student struct {
	gorm.Model
	StudentId    string `json:"studentid" gorm:"type:varchar(20); not null; unique"`
	StudentName  string `json:"studentname" gorm:"type:varchar(20); not null;"`
	StudentSex   string `json:"studentsex" gorm:"type:varchar(20); not null"`
	StudentSdept string `json:"studentsdept" gorm:"type:varchar(20); not null"`
	IsDel        bool   `json:"isdel" form:"isdel" gorm:"type:boolean default false;"`
}

func getJson(c *gin.Context) Student {
	json := make(map[string]string, 1024)
	c.ShouldBind(&json)
	studentId := json["studentid"]
	studentName := json["studentname"]
	studentSex := json["studentsex"]
	studentSdept := json["studentsdept"]

	student := Student{
		StudentId:    studentId,
		StudentName:  studentName,
		StudentSex:   studentSex,
		StudentSdept: studentSdept,
	}
	return student
}

func AddStudent(c *gin.Context) (Student, int64, error) {
	student := getJson(c)
	var total int64
	db.Table("students").Where("student_id = ?", student.StudentId).Count(&total)
	if total == 0 {
		err := db.Table("students").Create(&student).Error
		return student, total, err
	}
	return student, total, nil
}

func UpdateStudent(c *gin.Context) (Student, error) {
	student := getJson(c)
	err := db.Table("students").Where("student_id = ?", student.StudentId).Updates(&student).Error
	return student, err
}

func GetAllStudent(StudentParam map[string]interface{}) ([]Student, int64, error) {
	var stuData []Student
	pagenum := StudentParam["pagenum"].(int)
	pagesize := StudentParam["pagesize"].(int)
	query := StudentParam["query"].(string)
	fmt.Println("query = ", query)
	if query == "" {
		var total int64

		err := db.Table("students").Where("is_del = false").Count(&total).Error
		if err != nil {
			return stuData, 0, err
		}

		err = db.Table("students").Where("is_del = false").Offset((pagenum - 1) * pagesize).Limit(pagesize).Find(&stuData).Error
		return stuData, total, err
	}
	stuID := query
	var student Student
	err := db.Table("students").Where("student_id = ?", stuID).First(&student).Error
	stuData = append(stuData, student)
	return stuData, 1, err
}

func DelStudent(c *gin.Context) error {
	id := c.Params.ByName("id")
	err := db.Table("students").Where("student_id = ?", id).Update("is_del", true).Error
	return err
}
